package com.xujc.dao.imp;

import com.xujc.dao.IReviewDAO;
import com.xujc.entity.DiscuseEntity;
import com.xujc.entity.FormEntity;
import com.xujc.entity.ReviewEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

/**
 * Created by xujc on 6/17/15.
 */
public class ReviewDAO extends HibernateDaoSupport implements IReviewDAO {
    @Override
    public void makeReview(int d_id, int u_id, String content) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("from DiscuseEntity where DId= ?");
        query.setParameter(0, d_id);
        DiscuseEntity entities= (DiscuseEntity) query.uniqueResult();
        Collection<ReviewEntity> reviewsByDId = entities.getReviewsByDId();
        int max=0;
        if (reviewsByDId.size()==0){
            max=0;
        } else {
            ReviewEntity maxE = Collections.max(reviewsByDId, new Comparator<ReviewEntity>() {
                @Override
                public int compare(ReviewEntity o1, ReviewEntity o2) {
                    return o1.getFloor() - o2.getFloor();
                }
            });
            max=maxE.getFloor();
        }


        ReviewEntity entity=new ReviewEntity();
        entity.setContent(content);
        entity.setDId(d_id);
        entity.setUId(u_id);
        entity.setFloor(max + 1);
        session.save(entity);

        FormEntity formByFId = entities.getFormByFId();
        formByFId.setLastActive(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        session.save(formByFId);

        entities.setLastEdit(Timestamp.valueOf(LocalDateTime.now()));
        session.save(entities);

        transaction.commit();
        session.close();
    }
}
